package ao

import (
	"errors"
	compb "gitee.com/micro-services/protocol/common"
	pb "gitee.com/micro-services/protocol/user/server"
	"micro.user.server/dao"
	"micro.user.server/models"
	"micro.user.server/utils"
	"time"
)

func CreatHotelUser(req *pb.CreateUserReq) error {
	// 1.校验手机号，邮箱
	if !utils.IsMobile(req.Phone) {
		return errors.New("手机号码错误,请输入正确的手机号")
	}
	if !utils.IsEmail(req.Email) {
		return errors.New("邮箱错误,请输入正确的邮箱地址")
	}
	if !utils.IsPassword(req.PassWord) {
		return errors.New("密码格式不正确,密码需包含数字,大小写字母,密码长度为8~20位")
	}
	users := make([]*models.VsHUser, 0)
	users = append(users, &models.VsHUser{
		UserName:    req.UserName,
		Password:    utils.MD5(req.PassWord),
		Phone:       req.Phone,
		Email:       req.Email,
		Role:        req.Role,
		HotelId:     req.HotelID,
		IsDelete:    0,
		CreatedTime: time.Now().Unix(),
		UpdatedTime: time.Now().Unix(),
	})

	return dao.CreateHotelUser(users)
}

func UsrList(req *pb.QueryUserInfoReq) ([]*compb.UserInfo, error) {
	userIDList := make([]interface{}, 0)

	for _, v := range req.UserIDList {
		userIDList = append(userIDList, v)
	}

	users, err := dao.UsrList(req.HotelID, userIDList)
	if err != nil {
		return nil, err
	}

	list := make([]*compb.UserInfo, 0)
	for _, v := range users {
		list = append(list, &compb.UserInfo{
			UserID:     v.UserId,
			UserName:   v.UserName,
			Phone:      v.Phone,
			Email:      v.Email,
			Role:       v.Role,
			HotelID:    v.HotelId,
			HotelName:  "",
			CreateTime: "",
		})
	}

	return list, nil
}

func UpdateUser(req *pb.UpdateUserInfoReq) error {
	var pwd string
	if req.PassWord != "" {
		if !utils.IsPassword(req.PassWord) {
			return errors.New("密码格式不正确,密码需包含数字,大小写字母,密码长度为8~20位")
		}
		pwd = utils.MD5(req.PassWord)
	}
	// 1.校验手机号，邮箱
	if req.Phone != "" {
		if !utils.IsMobile(req.Phone) {
			return errors.New("手机号码错误,请输入正确的手机号")
		}
	}
	if req.Email != "" {
		if !utils.IsEmail(req.Email) {
			return errors.New("邮箱错误,请输入正确的邮箱地址")
		}
	}

	user := models.VsHUser{
		UserId:      req.UserID,
		UserName:    req.UserName,
		Password:    pwd,
		Phone:       req.Phone,
		Email:       req.Email,
		Role:        req.Role,
		HotelId:     req.HotelID,
		UpdatedTime: time.Now().Unix(),
	}

	return dao.UpdateUser(user)
}

func DeleteUser(req *pb.DeleteUserReq) error {
	userIDList := make([]interface{}, 0)
	for _, v := range req.UserIDList {
		userIDList = append(userIDList, v)
	}

	return dao.DeleteUser(userIDList)
}
